package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser queryTodayBest(Long userId) {
//        db.getCollection('recommend_user').find({toUserId:1}).sort({score:-1}).limit(1)
        Query query = new Query(Criteria.where("toUserId").is(userId)); //构建条件
        query.with(Sort.by(Sort.Direction.DESC,"score"));//排序
        query.limit(1); //取第一个
        return  mongoTemplate.findOne(query,RecommendUser.class);
    }

    @Override
    public PageResult queryRecommendation(Long userId, Integer page, Integer pagesize) {
//        db.recommend_user.find({toUserId:1}).sort({score:-1}).limit(10).skip(1)  (page-1)*pagesize
//        db.recommend_user.find({toUserId:1}).sort({score:-1}).limit(10).skip(11)
//        db.recommend_user.find({toUserId:1}).sort({score:-1}).limit(10).skip(21)

        Query query = new Query(Criteria.where("toUserId").is(userId)); //构建条件
        query.with(Sort.by(Sort.Direction.DESC,"score"));//排序
        query.limit(pagesize).skip( (page-1)*pagesize +1 );
        List<RecommendUser> list = mongoTemplate.find(query, RecommendUser.class);
        long count = mongoTemplate.count(query, RecommendUser.class);
        return new PageResult(page,pagesize,(int)count,list);// Integer page,Integer pagesize,int counts,List list
    }

    @Override
    public Long queryScore(Long userId, Long toUserId) {
//        查询两个人的缘分值   把张三推荐给李四      userId 张三    toUserId lisiId

        Query query = new Query(Criteria.where("toUserId").is(toUserId).and("userId").is(userId)); //构建条件
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if(recommendUser!=null){
            return recommendUser.getScore().longValue();
        }
        return 88L;
    }

    @Override
    public void delete(Long toUserId, Long userId) {
//        删除推荐给当前登录人的某一个用户 delete recommend_user where toUserId=当前登录人 and userId=??
        Query query = new Query(Criteria.where("toUserId").is(toUserId).and("userId").is(userId));
        mongoTemplate.remove(query,RecommendUser.class);
    }
}
